package sol.leetcode;

import java.util.Arrays;

/**
 * Spiral Matrix II
 */
public class Issue059 {
    public int[][] generateMatrix(int n) {
        int start = 0, end = n - 1;
        int[][] A = new int[n][n];
        int v = 1;
        while (start <= end)
            v = generate(start++, end--, A, v);
        return A;
    }

    private int generate(int start, int end, int[][] A, int v) {
        if (start == end) {
            A[start][start] = v++;
            return v;
        }
        for (int j = start; j < end; ++j)
            A[start][j] = v++;
        for (int i = start; i < end; ++i)
            A[i][end] = v++;
        for (int j = end; j > start; --j)
            A[end][j] = v++;
        for (int i = end; i > start; --i)
            A[i][start] = v++;
        return v;
    }

    public static void main(String[] args) {
        int n = 1;
        int[][] matrix = new Issue059().generateMatrix(n);
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}
